<template>
  <div>
    <el-container class="main-el-contarner">
      <el-main>
        <div>
          <el-tabs
            v-model="activeName"
            @tab-click="tbasclick"
            class="tabsbox"
            :before-leave="beforeLeave"
          >
            <el-tab-pane label="设备组" name="group">
              <div class="kanbao-bigbox">
                <div class="righttop-search-box" ref="fixedRef">
                  <el-form
                    :inline="true"
                    :model="param"
                    label-width="100px"
                    @submit.native.prevent
                  >
                    <el-form-item label="" label-width="10px">
                      <el-input
                        placeholder="请输入设备组名关键字检索"
                        clearable
                        v-model="param.name"
                        size="small"
                        style="width: 350px"
                        @keyup.enter.native="onSearch"
                      >
                        <i slot="prefix" class="el-input__icon el-icon-search"></i>
                      </el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" size="small" @click="onSearch"
                        >查找</el-button
                      >
                    </el-form-item>

                    <el-form-item style="float: right">
                      <el-button type="text" style="color: #18bc9c" @click="handleAdd"
                        ><i class="el-icon-plus"></i> 新增设备组</el-button
                      >
                    </el-form-item>
                  </el-form>
                </div>
                <div class="container-box">
                  <el-table
                    border
                    stripe
                    ref="talbes"
                    :data="tabledatas"
                    max-height="480px"
                    @row-dblclick="rowdbclick"
                    :header-cell-style="{
                      background: '#cfcfcf',
                      color: '#000000',
                      'text-align': 'center',
                    }"
                    :cell-style="{ 'text-align': 'center' }"
                    style="width: 100%"
                    size="small"
                    @selection-change="selectionChange"
                    @row-click="handleRowClick"
                  >
                    <el-table-column
                      type="selection"
                      header-align="center"
                      width="60"
                    ></el-table-column>
                    <el-table-column prop="group_name" label="设备组名">
                    </el-table-column>
                    <el-table-column prop="bom_name" label="设备机型"> </el-table-column>
                    <el-table-column prop="memo" label="备注"> </el-table-column>
                    <el-table-column fixed="right" label="操作" width="160">
                      <template slot-scope="scope">
                        <el-button
                          @click.stop="editClick(scope.row)"
                          type="text"
                          icon="el-icon-edit"
                          style="color: #18bc9c; margin: 5px; padding: 0px"
                          >编辑</el-button
                        >
                        |
                        <el-button
                          @click.stop="delClick(scope.row)"
                          type="text"
                          icon="el-icon-delete"
                          style="color: #ff0000; margin: 5px; padding: 0px"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>

                  <div class="pagebox">
                    <el-pagination
                      @size-change="sizeChange"
                      @current-change="currentChange"
                      :current-page="param.pageNo"
                      :page-sizes="[10, 30, 50, 100, 500]"
                      :page-size="param.limit"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="dataTotal"
                    >
                    </el-pagination>
                  </div>
                </div>
                <div>
                  <el-dialog
                    v-if="dialogVisible"
                    v-dialogDrag
                    :title="dialogtitle"
                    :visible.sync="dialogVisible"
                    width="70%"
                    top="30px"
                    :class="dialogVisible == true ? 'action01' : 'action02'"
                    :before-close="handleClose"
                  >
                    <el-form
                      :model="formData.datas[0]"
                      :inline="true"
                      :rules="rules"
                      ref="formdata"
                    >
                      <el-form-item
                        label="设备组名"
                        :label-width="formLabelWidth"
                        prop="group_name"
                      >
                        <el-input
                          v-model="formData.datas[0].group_name"
                          autocomplete="off"
                          style="width: 215px"
                          placeholder="设备组名"
                        ></el-input>
                      </el-form-item>
                      <el-form-item
                        label="设备机型"
                        :label-width="formLabelWidth"
                        prop="bom_name"
                      >
                        <el-input
                          v-model="formData.datas[0].bom_name"
                          autocomplete="off"
                          style="width: 215px"
                          placeholder="设备机型"
                          ><i slot="suffix" class="el-icon-more" @click="device_model"></i
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="备注" :label-width="formLabelWidth">
                        <el-input
                          v-model="formData.datas[0].memo"
                          autocomplete="off"
                          style="width: 540px"
                          placeholder="备注"
                        ></el-input>
                      </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                      <el-button @click="handleClose">取 消</el-button>
                      <el-button type="primary" @click="save">保 存</el-button>
                    </span>
                  </el-dialog>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="设备组成员" name="groupmembers">
              <div class="action01">
                <devicegroupmembers
                  :groupData="selectionChangeData"
                  ref="Devicegroupmembersmethod"
                ></devicegroupmembers>
              </div>
            </el-tab-pane>
          </el-tabs>
          <div>
            <el-dialog
              v-if="dialogModel"
              v-dialogDrag
              title="设备机型"
              :visible.sync="dialogModel"
              width="70%"
              top="30px"
              :class="dialogVisible == true ? 'action01' : 'action02'"
            >
              <device_model @getcomData="getModelData"></device_model>
              <span slot="footer" class="dialog-footer">
                <!-- <el-button @click="dialogModel = false">取 消</el-button> -->
                <el-button type="primary" @click="bind">确 定</el-button>
              </span>
            </el-dialog>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import { getlist, getgridsave, getdeletes } from "@/api/message/list";
import devicegroupmembers from "@/views/message/components/devicegroupmembers.vue";
import device_model from "@/views/message/components/device_model.vue";
export default {
  name: "devicegroup",
  components: { devicegroupmembers, device_model },
  data() {
    return {
      dialogModel: false,
      param: {
        funId: "msg_device_group",
        baseSQL: "",
        warnStatus: "",
        name: "",
        offset: 0,
        pageNo: 1,
        limit: 10,
      },
      activeName: "group",
      dataTotal: 0,
      tabledatas: [],
      dialogtitle: "",
      dialogVisible: false,
      formData: {
        is_iot: false,
        funId: "msg_device_group",
        datas: [
          {
            group_name: "",
            memo: "",
            bom_name: "", //设备机型
            bom_id: "", //机型ID
          },
        ],
      },
      formLabelWidth: "100px",
      rules: {
        group_name: [{ required: true, message: "设备组名称必填", trigger: "blur" }],
        bom_name: [{ required: true, message: "设备机型必填", trigger: "blur" }],
      },
      selectionChangeData: "",
      modelData: "",
    };
  },
  mounted() {
    this.getDatas();
    window.addEventListener("scroll", this.handleScroll, true);
    // this.handleClick()
  },
  created() {},
  methods: {
    //监听浏览器滚动距离
    handleScroll(e) {
      let scrollTop = e.target.scrollTop;
      if (scrollTop > 30) {
        this.$refs.fixedRef.style.top = 0;
      } else {
        this.$refs.fixedRef.style.top = "60px";
      }
    },

    //判断表单是否变化
    handleClose() {
      let num = 0;
      for (const key in this.formData.datas[0]) {
        if (this.formData.datas[0][key] == "") {
          // num = num + 0
          num += 0;
        } else if (this.formData.datas[0][key] == null) {
          // num = num + 0
          num += 0;
        } else {
          // num = num + 1
          num += 1;
        }
      }
      if (this.dialogtitle == "新增设备组") {
        if (num != 0) {
          this.$confirm("表单未保存,是否关闭?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.dialogVisible = false;
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "取消关闭",
              });
            });
        } else {
          this.dialogVisible = false;
        }
      } else {
        // console.log('222',JSON.stringify(this.formData.datas[0]))
        // console.log('22222',sessionStorage.getItem("initForm"))
        if (
          JSON.stringify(this.formData.datas[0]) == sessionStorage.getItem("initForm")
        ) {
          this.dialogVisible = false;
        } else {
          this.$confirm("表单未保存,是否关闭?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.dialogVisible = false;
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "取消关闭",
              });
            });
        }
      }
      // console.log('num',num)
    },
    getModelData(e) {
      // console.log('model',e)
      this.modelData = e;
    },
    bind() {
      if (this.modelData.length == "0") {
        this.$message({
          message: "请选择一条数据",
          type: "error",
        });
      } else {
        this.formData.datas[0].bom_name = this.modelData[0].bom_name;
        this.formData.datas[0].bom_id = this.modelData[0].bom_id;
        this.$refs["formdata"].validate((valid) => {});
        this.dialogModel = false;
      }
    },
    handleClick() {
      this.$refs.Devicegroupmembersmethod.getDatas();
    },
    device_model() {
      this.dialogModel = true;
    },
    //标签按钮
    tbasclick(tab) {
      // this.toggleSelection()
      // console.log('tab.name', this.selectionChangeData)
      if (this.selectionChangeData != "") {
        this.handleClick();
      }
    },

    beforeLeave() {
      // console.log('this.selectionChangeData', this.selectionChangeData)
      if (this.selectionChangeData == "") {
        this.$message({
          message: "请选择并仅选择一条记录后再操作",
          type: "error",
        });
        return false;
      } else if (this.selectionChangeData == undefined) {
        this.$message({
          message: "请选择并仅选择一条记录后再操作",
          type: "error",
        });
        return false;
      } else {
        return true;
      }
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.talbes.toggleRowSelection(row, false);
        });
        this.selectionChangeData = "";
      } else {
        this.$refs.talbes.clearSelection();
      }
    },
    //添加按钮
    handleAdd() {
      if (this.$refs["formdata"]) {
        this.$refs["formdata"].resetFields();
      }
      this.dialogVisible = true;
      this.dialogtitle = "新增设备组";
      this.formData.datas[0].group_name = "";
      this.formData.datas[0].group_id = "";
      this.formData.datas[0].memo = "";
      this.formData.datas[0].bom_name = "";
      this.formData.datas[0].bom_id = "";
    },
    //编辑按钮
    editClick(e) {
      this.getDatas();
      if (this.$refs["formdata"]) {
        this.$refs["formdata"].resetFields();
      }
      this.dialogVisible = true;
      this.dialogtitle = "编辑设备组";
      this.formData.datas[0] = e;
      sessionStorage.setItem("initForm", JSON.stringify(this.formData.datas[0]));
    },
    //双击打开编辑页面
    rowdbclick(row) {
      this.getDatas();
      this.dialogVisible = true;
      this.dialogtitle = "编辑设备组";
      this.formData.datas[0] = row;
      if (this.$refs["formdata"]) {
        this.$refs["formdata"].resetFields();
      }
      sessionStorage.setItem("initForm", JSON.stringify(this.formData.datas[0]));
    },
    //添加数据
    addgroup() {
      getgridsave(this.formData).then((res) => {
        if (res.data.code == "200") {
          this.$message({
            message: "添加设备组成功",
            type: "success",
          });
          this.getDatas();
        } else {
          this.$message({
            message: "添加设备失败",
            type: "error",
          });
        }
      });
    },
    //修改数据
    updategroup() {
      getgridsave(this.formData).then((res) => {
        if (res.data.code == "200") {
          this.$message({
            message: "编辑设备组成功",
            type: "success",
          });
          this.getDatas();
        } else {
          this.$message({
            message: "编辑设备组成功",
            type: "error",
          });
        }
      });
    },
    // 复选框按钮
    selectionChange(e) {
      // this.selectionChangeData.group_id=e[0].group_id
      // this.selectionChangeData.group_name=e[0].group_name
      if (e.length != "1") {
        this.$message({
          message: "请选择并仅选择一条记录后再操作",
          type: "error",
        });
        this.toggleSelection(e);
      } else {
        this.selectionChangeData = e[0];
      }
    },
    handleRowClick(e) {
      this.$refs.talbes.toggleRowSelection(e);
      const _selectData = this.$refs.talbes.selection;
      this.selectionChange(_selectData);
    },
    //删除数据
    delClick(info) {
      var tablefromdata = {
        funId: "msg_device_group",
        ids: info.group_id + ";",
      };

      this.$confirm(`删除${info.group_name}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        getdeletes(tablefromdata).then((res) => {
          // console.log('res', res)
          // if(res.status=='200'){
          if (res.data.code == "200") {
            this.$message({
              message: "删除告警成功",
              type: "success",
            });
            this.getDatas();
          } else {
            this.$message({
              message: "删除告警失败",
              type: "error",
            });
          }
          // }
          // else{
          //   this.$message({
          //       message: '删除告警失败',
          //       type: 'error'
          //   });
          //}
        });
      });
    },
    //保存按钮
    save() {
      this.$refs["formdata"].validate((valid) => {
        if (valid) {
          // console.log('valid',valid)
          if (this.formData.datas[0].group_id) {
            this.updategroup();
            this.dialogVisible = false;
          } else {
            this.addgroup();
            this.dialogVisible = false;
          }
        }
      });
    },
    // 数据搜索按钮
    onSearch() {
      this.param.pageNo = 1;
      this.getDatas();
    },
    getDatas() {
      if (this.param.name == "") {
        this.param.baseSQL = "";
      } else {
        this.param.baseSQL = 'group_name like"%' + this.param.name + '%"';
      }
      getlist(this.param).then((res) => {
        if (res.status == "200") {
          let resdata = res.data;
          this.tabledatas = resdata.rows;
          this.dataTotal = resdata.total;
        }
      });
    },

    indexMethod(index) {
      return (this.param.pageNo - 1) * this.param.limit + index + 1;
    },
    sizeChange(val) {
      this.param.limit = val;
      this.getDatas();
    },
    currentChange(val) {
      this.param.pageNo = val;
      this.param.offset = (val - 1) * this.param.limit;
      this.getDatas();
    },
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.handleScroll);
  },
};
</script>
<style>
.kanbao-bigbox .el-loading-spinner .el-loading-text {
  color: #666 !important;
}
</style>
<style scoped>
.el-main {
  padding: 0px !important;
}

.dialog-footer {
  margin-top: -50px;
}

/* .kanbao-bigbox {
  margin-top: 0px;
  animation: zoomIn 0.5s;
} */
</style>
<style scoped>
/* .action01 {
  animation: zoomIn 0.5s;
  animation-iteration-count: 1;
}

.action02 {
  animation: zoomOut 0.5s;
  animation-iteration-count: 1;
} */

/* .action03{
  animation: zoomIn 0.5s;
} */

.righttop-search-box {
  background: #f8f8f8;
  padding: 8px 20px 7px 20px;
  border-bottom: 1px solid #ececec;
  margin-top: 10px;
  position: fixed;
  top: 50px;
  width: calc(100% - 65px);
  z-index: 4;
}

.righttop-search-box .el-form-item {
  margin-bottom: 0px !important;
}

.container-box {
  padding-top: 10px;
  margin: 50px 0;
}

.pagebox {
  text-align: right;
  padding: 10px;
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;
  background-color: #ececec;
  z-index: 4;
}

.tabsbox {
  padding: 10px;
}
</style>
